package com.xxx.video.login.activitys;

import android.graphics.Color;
import android.graphics.Typeface;
import android.location.Location;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.google.android.gms.tasks.OnSuccessListener;
import com.google.gson.Gson;
import com.xxx.video.R;
import com.xxx.video.commen.activitys.BaseActivity;
import com.xxx.video.commen.configs.UserManager;
import com.xxx.video.commen.events.LoginSuccessEvent;
import com.xxx.video.commen.utils.FontCacheUtils;
import com.xxx.video.commen.utils.ListUtils;
import com.xxx.video.commen.utils.LocationUtils;
import com.xxx.video.commen.utils.StatusBarUtil;
import com.xxx.video.commen.utils.StringUtils;
import com.xxx.video.commen.utils.ToastUtils;
import com.xxx.video.commen.views.FontTextView;
import com.xxx.video.commen.views.IosSingleChoosePopupWindow;
import com.xxx.video.login.beans.RegisterBundleInfoBean;
import com.xxx.video.login.beans.RegisterSecondBean;
import com.xxx.video.login.beans.RegisterSuccessBean;
import com.xxx.video.login.beans.SecurityOptionsBean;
import com.xxx.video.login.presenters.IRegisterSecondView;
import com.xxx.video.login.presenters.RegisterSecondPresenter;
import com.xxx.video.mine.activitys.CommonWebViewActivity;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class RegisterSecondActivity extends BaseActivity<RegisterSecondPresenter> implements IRegisterSecondView {


    @BindView(R.id.tv_register_second_activity_first_question_title)
    TextView tvRegisterSecondActivityFirstQuestionTitle;
    @BindView(R.id.tv_register_second_activity_first_question)
    TextView tvRegisterSecondActivityFirstQuestion;
    @BindView(R.id.et_register_second_activity_first_answer)
    EditText etRegisterSecondActivityFirstAnswer;
    @BindView(R.id.tv_register_second_activity_second_question)
    TextView tvRegisterSecondActivitySecondQuestion;
    @BindView(R.id.tv_register_second_activity_second_question_title)
    TextView tvRegisterSecondActivitySecondQuestionTitle;
    @BindView(R.id.et_register_second_activity_second_answer)
    EditText etRegisterSecondActivitySecondAnswer;
    @BindView(R.id.tv_register_second_activity_third_question)
    TextView tvRegisterSecondActivityThirdQuestion;
    @BindView(R.id.tv_register_second_activity_third_question_title)
    TextView tvRegisterSecondActivityThirdQuestionTitle;
    @BindView(R.id.et_register_second_activity_third_answer)
    EditText etRegisterSecondActivityThirdAnswer;
    @BindView(R.id.cb_register_second_activity_user_agency)
    CheckBox cbRegisterSecondActivityUserAgency;
    @BindView(R.id.tv_register_second_activity_user_agency)
    TextView tvRegisterSecondActivityUserAgency;
    /**
     * register info bean
     */
    private RegisterBundleInfoBean mRegisterBundleInfoBean;
    /**
     * get security list
     */
    private List<SecurityOptionsBean.ListBean> securityList;
    /**
     * Question list
     */
    public SecurityOptionsBean.ListBean[] questionList = new SecurityOptionsBean.ListBean[3];

    /**
     * question List
     */
    public HashMap<String, Integer> questionListMap = new HashMap<>();

    @Override
    public void initToolbarData() {
        super.initToolbarData();
        showActionBar();
        StatusBarUtil.getInstance().setStatusBarTransparent(this, true);
        setActionBarTitle(R.string.title_register_first_activity);
        Typeface customFont = FontCacheUtils.getInstance().getTypeface(FontTextView.ttf3, this);
        etRegisterSecondActivityFirstAnswer.setTypeface(customFont);
        etRegisterSecondActivitySecondAnswer.setTypeface(customFont);
        etRegisterSecondActivityThirdAnswer.setTypeface(customFont);
        cbRegisterSecondActivityUserAgency.setTypeface(customFont);
    }

    @Override
    protected RegisterSecondPresenter createPresenter() {
        return new RegisterSecondPresenter(this, this);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_register_second;
    }

    @Override
    public void initData(Bundle extras) {
        showLayoutStatus(1);
        if (extras != null) {
            mRegisterBundleInfoBean = extras.getParcelable("RegisterBundleInfo");
        }
        initPreview();
        initUserAgency();
    }

    @Override
    public void showRootLayoutStatus(int status) {
        showLayoutStatus(status);
    }

    @OnClick({R.id.tv_register_second_activity_first_question, R.id.tv_register_second_activity_second_question,
            R.id.tv_register_second_activity_third_question, R.id.tv_register_second_activity_register})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_register_second_activity_first_question:
                showCheckOptionPopupWindow(0);
                break;
            case R.id.tv_register_second_activity_second_question:
                showCheckOptionPopupWindow(1);
                break;
            case R.id.tv_register_second_activity_third_question:
                showCheckOptionPopupWindow(2);
                break;
            case R.id.tv_register_second_activity_register:
                LocationUtils.getLocation(this, (OnSuccessListener<Location>) location -> {
                    if (location != null) {
                        getPresenter().register(mRegisterBundleInfoBean, String.valueOf(location.getLongitude()), String.valueOf(location.getLatitude()));
                    } else {
                        getPresenter().register(mRegisterBundleInfoBean, "", "");
                    }
                });
                break;
            default:
                break;
        }

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        RegisterSecondBean registerSecondBean = new RegisterSecondBean();
        registerSecondBean.questionList = questionList;
        registerSecondBean.firstAnswer = getFirstAnswer();
        registerSecondBean.secondAnswer = getSecondAnswer();
        registerSecondBean.thirdAnswer = getThirdAnswer();
        String json = new Gson().toJson(registerSecondBean);
        UserManager.getInstance().putSaveSecurityOptionsBean(json);
    }

    @Override
    public void initPreview() {
        tvRegisterSecondActivityFirstQuestionTitle.setText(StringUtils.getInstance().getString(R.string.tv_register_second_activity_first_question_title) + StringUtils.getInstance().getString(R.string.tv_register_second_activity_question_title));
        tvRegisterSecondActivitySecondQuestionTitle.setText(StringUtils.getInstance().getString(R.string.tv_register_second_activity_second_question_title) + StringUtils.getInstance().getString(R.string.tv_register_second_activity_question_title));
        tvRegisterSecondActivityThirdQuestionTitle.setText(StringUtils.getInstance().getString(R.string.tv_register_second_activity_third_question_title) + StringUtils.getInstance().getString(R.string.tv_register_second_activity_question_title));

        String json = UserManager.getInstance().getSaveSecurityOptionsBean();
        if (!TextUtils.isEmpty(json)) {
            try {
                RegisterSecondBean registerSecondBean = new Gson().fromJson(json, RegisterSecondBean.class);
                questionList = registerSecondBean.questionList;
                if (!TextUtils.isEmpty(registerSecondBean.firstAnswer)) {
                    etRegisterSecondActivityFirstAnswer.setText(registerSecondBean.firstAnswer);
                }
                if (!TextUtils.isEmpty(registerSecondBean.secondAnswer)) {
                    etRegisterSecondActivitySecondAnswer.setText(registerSecondBean.secondAnswer);
                }
                if (!TextUtils.isEmpty(registerSecondBean.thirdAnswer)) {
                    etRegisterSecondActivityThirdAnswer.setText(registerSecondBean.thirdAnswer);
                }
                if (questionList != null || questionList.length > 0) {
                    if (questionList[0] != null) {
                        tvRegisterSecondActivityFirstQuestion.setText(questionList[0].fDatadictDesc);
                        questionListMap.put(questionList[0].fDatadictId, 0);
                    }
                    if (questionList[1] != null) {
                        tvRegisterSecondActivitySecondQuestion.setText(questionList[1].fDatadictDesc);
                        questionListMap.put(questionList[1].fDatadictId, 1);
                    }
                    if (questionList[2] != null) {
                        tvRegisterSecondActivityThirdQuestion.setText(questionList[2].fDatadictDesc);
                        questionListMap.put(questionList[2].fDatadictId, 2);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void showCheckOptionPopupWindow(int number) {
        if (ListUtils.isEmpty(securityList)) {
            getPresenter().getSecurityOptions(number);
        } else {
            IosSingleChoosePopupWindow iosSingleChooseDialog = new IosSingleChoosePopupWindow(this);
            ArrayList<String> stringArrayList = new ArrayList<>();
            for (SecurityOptionsBean.ListBean listBean : securityList) {
                stringArrayList.add(listBean.fDatadictDesc);
            }
            iosSingleChooseDialog.setData(StringUtils.getInstance().getString(R.string.dialog_choose_register_security_title),
                    StringUtils.getInstance().getString(R.string.dialog_choose_register_security_cancel), stringArrayList);
            iosSingleChooseDialog.setOnIosSingleChooseItemClickListener((string, position, type) -> {
                if (!TextUtils.isEmpty(string)) {
                    SecurityOptionsBean.ListBean question = securityList.get(position);
                    if (questionListMap.get(question.fDatadictId) == null) {
                        questionList[number] = question;
                        if (number == 0) {
                            tvRegisterSecondActivityFirstQuestion.setText(question.fDatadictDesc);
                        } else if (number == 1) {
                            tvRegisterSecondActivitySecondQuestion.setText(question.fDatadictDesc);
                        } else if (number == 2) {
                            tvRegisterSecondActivityThirdQuestion.setText(question.fDatadictDesc);
                        }
                        questionListMap.put(question.fDatadictId, number);
                    } else {
                        ToastUtils.showError(StringUtils.getInstance().getString(R.string.tip_register_second_check_security_question_is_same));
                    }
                }
            });
            iosSingleChooseDialog.showAtLocation(getWindow().getDecorView());
            lightof();
            iosSingleChooseDialog.setOnDismissListener(this::lighton);
        }
    }

    @Override
    public void initSecurityData2View(SecurityOptionsBean successOb, int number) {
        securityList = successOb.list;
        showCheckOptionPopupWindow(number);
    }

    @Override
    public SecurityOptionsBean.ListBean[] getQuestionList() {
        return questionList;
    }

    @Override
    public String getFirstAnswer() {
        return etRegisterSecondActivityFirstAnswer.getText().toString().trim();
    }

    @Override
    public String getSecondAnswer() {
        return etRegisterSecondActivitySecondAnswer.getText().toString().trim();
    }

    @Override
    public String getThirdAnswer() {
        return etRegisterSecondActivityThirdAnswer.getText().toString().trim();
    }

    @Override
    public void registerSuccess(RegisterSuccessBean successOb) {
        ToastUtils.showSuccess(StringUtils.getInstance().getString(R.string.tip_login_success));
        UserManager.getInstance().putToken(successOb.token);
        UserManager.getInstance().putUserId(successOb.user.userId);
        UserManager.getInstance().putUserName(mRegisterBundleInfoBean.userName);
        EventBus.getDefault().post(new LoginSuccessEvent());
        finish();
    }

    public void initUserAgency() {
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder();
        String title = StringUtils.getInstance().getString(R.string.login_activity_user_agency_first);
//        String userAgreement = StringUtils.getInstance().getString(R.string.login_activity_user_agency_second);
        String userPrivacyPolicy = StringUtils.getInstance().getString(R.string.login_activity_user_agency_third);
        ;
//        String center = StringUtils.getInstance().getString(R.string.login_activity_user_agency_forth);
//        String accountVerificationServiceAgreement = StringUtils.getInstance().getString(R.string.login_activity_user_agency_fifth);

        spannableStringBuilder.append(title);
//        spannableStringBuilder.append(userAgreement);
//        spannableStringBuilder.append(userPrivacyPolicy);
//        spannableStringBuilder.append(center);
//        spannableStringBuilder.append(accountVerificationServiceAgreement);

//        /*
//         * init userAgreement
//         */
//        ClickableSpan clickableSpan1 = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//
//            }
//        };
//        int start1 = title.length();
//        int end1 = title.length() + userAgreement.length();
//        spannableStringBuilder.setSpan(clickableSpan1, start1, end1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ForegroundColorSpan foregroundColorSpan1 = new ForegroundColorSpan(Color.parseColor("#01A0F1"));
//        spannableStringBuilder.setSpan(foregroundColorSpan1, start1, end1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//        /*
//         * init userPrivacyPolicy
//         */
//        ClickableSpan clickableSpan2 = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//            }
//        };
//        int start2 = title.length() + userAgreement.length();
//        int end2 = title.length() + userAgreement.length() + userPrivacyPolicy.length();
//        spannableStringBuilder.setSpan(clickableSpan2, start2, end2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ForegroundColorSpan foregroundColorSpan2 = new ForegroundColorSpan(Color.parseColor("#01A0F1"));
//        spannableStringBuilder.setSpan(foregroundColorSpan2, start2, end2, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//
//
//        /*
//         * init accountVerificationServiceAgreement
//         */
//        ClickableSpan clickableSpan3 = new ClickableSpan() {
//            @Override
//            public void onClick(View widget) {
//            }
//        };
//        int start3 = title.length() + userAgreement.length() + userPrivacyPolicy.length() + center.length();
//        int end3 = title.length() + userAgreement.length() + userPrivacyPolicy.length() + center.length() + accountVerificationServiceAgreement.length();
//        spannableStringBuilder.setSpan(clickableSpan3, start3, end3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//        ForegroundColorSpan foregroundColorSpan3 = new ForegroundColorSpan(Color.parseColor("#01A0F1"));
//        spannableStringBuilder.setSpan(foregroundColorSpan3, start3, end3, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

        tvRegisterSecondActivityUserAgency.setHighlightColor(getResources().getColor(android.R.color.transparent));
        tvRegisterSecondActivityUserAgency.setMovementMethod(LinkMovementMethod.getInstance());
        tvRegisterSecondActivityUserAgency.setText(spannableStringBuilder);
        tvRegisterSecondActivityUserAgency.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle bundle = new Bundle();
                bundle.putString("Url", "https://www.qiqas.com/#/privacyPolicy");
                intent2Activity(CommonWebViewActivity.class, bundle);
            }
        });
    }

    @Override
    public boolean isAgreeUserAgency() {
        if (cbRegisterSecondActivityUserAgency != null) {
            return cbRegisterSecondActivityUserAgency.isChecked();
        }
        return false;
    }
}
